package cn.huiyunche.admin.framework.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSONObject;

import cn.huiyunche.base.service.framework.utils.JdbcTemplateUtils;

public class MenuFilter extends OncePerRequestFilter {
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		
		String angular = request.getHeader("angular");
		String requestURI = request.getRequestURI();
		String contentPath = request.getContextPath();
		if (StringUtils.isBlank(angular)) {
			filterChain.doFilter(request, response);
		} else if (requestURI.equals(contentPath + "/menu") || requestURI.equals(contentPath + "/banner") || requestURI.equals(contentPath + "/menu/all")) {
			filterChain.doFilter(request, response);
		} else {
			// 检测菜单
			String menu = request.getHeader("menu");
			List<Long> userMenuList = this.getMenuIdsByRole(this.getSysAdminUserRole(this.getSysAdminUserId()));
			boolean isMyMenu = false;
			for (Long l : userMenuList) {
				if ((l + "").equals(menu)) {
					isMyMenu = true;
					break;
				}
			}
			if (StringUtils.isBlank(menu)) {
				isMyMenu = true;
			}
			if (isMyMenu) {
				filterChain.doFilter(request, response);
			} else {
				response.setHeader("Content-type", "text/html;charset=UTF-8");
				JSONObject j = new JSONObject();
				j.put("success", false);
				j.put("messageCode", null);
				j.put("message", "此请求不在你的菜单权限中");
				j.put("data", null);
				PrintWriter out = null;
				out = response.getWriter();
		    		out.write(j.toJSONString());
		    		out.flush();
		    		out.close();
			}
		}
	}

	/**
	 * 获取当前用户
	 * @param username
	 * @return
	 */
	private Long getSysAdminUserId() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		UserDetails ud = (UserDetails) authentication.getPrincipal();
		if (null != ud) {
			String username = ud.getUsername();
			String sql = "select id from sys_admin_user where username = '" + username + "'";
			return JdbcTemplateUtils.getJdbcTemplate().queryForObject(sql, Long.class);
		}
		return null;
	}
	
	/**
	 * 获取用户角色
	 * @param userId
	 * @return
	 */
	private Long getSysAdminUserRole(Long userId) {
		String sql = "select role_id from sys_admin_role_user where user_id = " + userId;
		return JdbcTemplateUtils.getJdbcTemplate().queryForObject(sql, Long.class);
	}
	
	/**
	 * 根据角色查询菜单列表
	 * @return
	 */
	private List<Long> getMenuIdsByRole(Long roleId) {
		String sql = "select menu_id from sys_admin_menu_role where role_id = " + roleId;
		return JdbcTemplateUtils.getJdbcTemplate().queryForList(sql, Long.class);
	}
}
